package com.wu.ezchat.test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLSyntaxErrorException;
import java.util.HashMap;
import java.util.Map;

public class SocketServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        Map<String, Socket> CLENT_MAP = new HashMap<>();
        try {
            server = new ServerSocket(1024);
            System.out.println("服务端已经启动，等待客户端连接");
            while (true) {
                Socket socket = server.accept();
                String ip = socket.getInetAddress().getHostAddress();
                String clientkey =ip+socket.getPort();
                CLENT_MAP.put(clientkey, socket);
                System.out.println("客户端已经连接，IP为"+ip+"，端口为"+socket.getPort());

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                InputStream inputStream = socket.getInputStream();
                                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                                String readData = bufferedReader.readLine();
                                System.out.println("收到客户端消息->" + readData);

                                CLENT_MAP.forEach((k,v)->{
                                    try {
                                        OutputStream outputStream =v.getOutputStream();
                                        PrintWriter printWriter = new PrintWriter(outputStream);
                                        printWriter.println(socket.getPort()+":"+readData);
                                        printWriter.flush();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                                break;
                            }

                        }
                    }
                }).start();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
